import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { STColumn, STComponent, STColumnBadge } from '@delon/abc/st';
import { SFSchema, SFComponent } from '@delon/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { environment } from '@env/environment';
import { NzTreeComponent, NzTreeNode } from 'ng-zorro-antd/tree';

@Component({
  selector: 'app-sys-resource',
  templateUrl: './resource.component.html',
})
export class SysResourceComponent implements OnInit {
  constructor(private http: _HttpClient, private msgSrv: NzMessageService) {
  }
  keyword: string = '';
  url = `${environment.sys.ctx}/sysResource/findByQueryParams`;

  selectResource: any = {};

  @ViewChild('sf', { static: false }) sf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      name: {
        type: 'string',
        title: '名称',
      },
    },
  };

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '代码', index: 'code' },
    { title: '名称', index: 'name' },
    { title: '链接', index: 'link' },
    { title: '类型', index: 'type' },
    { title: '图标', index: 'icon' },
    { title: '打开方式', index: 'target' },
    { title: '国际化', index: 'i18n' },
    { title: '排序', index: 'sort' },
    // { title: '头像', type: 'img', width: '50px', index: 'avatar' },
    { title: '创建时间', type: 'date', index: 'createdDate' },
    {
      title: '创建人',
      index: 'createdByName',
    },
    {
      title: '操作',
      width: 100,
      buttons: [
        // { text: '查看', click: (item: any) => `/form/${item.id}` },
        // { icon: 'edit', type: 'static', component: SysResourceEditComponent, click: 'reload', tooltip: `编辑` },
        {
          tooltip: `删除`,
          icon: 'delete',
          type: 'del',
          pop: {
            title: '是否确定删除?',
            okType: 'danger',
            icon: 'star',
          },
          click: (record, _modal, comp) => this.delete(record),
        },
      ],
    },
  ];

  @ViewChild('rootResourcesTree', { static: false }) rootResourcesTree!: NzTreeComponent;

  rootResources = [{ title: '资源树', key: '0', isExpanded: true, children: [] }];

  menu: any = { '0': { id: '0', code: '' } };

  ngOnInit() {
    this.treeExpandChange(this.rootResourcesTree.getTreeNodes()[0]);
  }

  delete(record:any) {
    this.http.post(`${environment.sys.ctx}/sysResource/deleteById/${record.key}`).subscribe(res => {
      this.msgSrv.success(`成功删除`);
      this.st.reload();
    });
  }
  release() {
    this.http.get(`${environment.sys.ctx}/sysResource/reload`).subscribe(res => {
      this.msgSrv.success(`成功发布`);
    });
  }

  add(node:any) {
    const parentCode = this.menu[node.key].code;
    this.selectResource = { parentId: node.key, code: `${parentCode}:` };
  }

  treeExpandChange(node: NzTreeNode, isSync: boolean = false): void {
    if ((node && node.getChildren().length === 0 && node.isExpanded) || isSync) {
      node.isLoading = true;
      const children:any[] = [];
      this.http.get(`${environment.sys.ctx}/sysResource/findByParentId/${node.key}`).subscribe(res => {
        if (res.length > 0) {
          res.forEach((element:any) => {
            this.menu[element.id] = element;
            children.push({ title: element.name, key: element.id });
          });
          node.clearChildren();
          node.addChildren(children);
          // tslint:disable-next-line: deprecation
          node.setExpanded(true);
        } else {
          node.isLeaf = true;
        }
        node.isLoading = false;
      });
    }
  }

  edit(node: NzTreeNode): void {
    if (node.key === '0') {
      this.add(node);
      return;
    }
    this.http.get(`${environment.sys.ctx}/sysResource/${node.key}`).subscribe(res => {
      this.selectResource = res;
      this.selectResource.roleIds = [];
      this.selectResource.roles.forEach((it:any) => this.selectResource.roleIds.push(it.id));
    });
  }
}
